package com.jt.service;

import com.jt.mapper.ItemDescMapper;
import com.jt.vo.ImageVO;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.reflect.generics.tree.VoidDescriptor;

import javax.imageio.ImageIO;
import javax.print.DocFlavor;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author :Colin
 * @version 创建时间: 2021/8/10 15:39
 */
@Service
public class FileServiceImpl implements FileService {
    /*@Autowired
    private ItemDescMapper itemDescMapper;*/
    private String localDir = "/usr/local/src/images";//原来的是在d盘下 images
    private String preUrlPath ="http://image.jt.com";
    @Override
    public ImageVO upload(MultipartFile file)  {
        //1.图片类型的校验
        String fileName = file.getOriginalFilename();
        fileName = fileName.toLowerCase();
        if(!fileName.matches("^.+\\.(jpg|png|gif)$")){
            return null;
        }
        //2.是否为 恶意程序
        try {
            //该对象是用于专门操作图片的API
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int height = bufferedImage.getHeight();
            int width = bufferedImage.getWidth();

            if (height == 0 || width == 0){
                return  null;
            }
            System.out.println("一切正常");

        //3.分目录存储文件
        //yyyy/MM/dd
        //3.1准备根目录

        String dateDir = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        String dirPath = localDir + dateDir;
        File dirFile = new File(dirPath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        //4.防止文件重名 UUID
        String uuid = UUID.randomUUID().toString().replace("-", "");
        int index = fileName.lastIndexOf(".");
        String fileType =fileName.substring(index);
        String realFileName = uuid + fileType;
        String realPath =dirPath+realFileName;
        file.transferTo(new File(realPath));
        //5.建立各种地址
        String virtualPath = dateDir + realFileName;
//        String urlPath = "https://gitee.com/static/images/logo-black.svg?t=158106664";
            String urlPath =preUrlPath+virtualPath;
            System.out.println("网络地址是"+urlPath);
            ImageVO imageVO = new ImageVO();
            imageVO.setVirtualPath(virtualPath).setUrlPath(urlPath).setFileName(realFileName);
            return imageVO;
        } catch (IOException e) {
            e.printStackTrace();
            return null;//如果程序执行报错,则返回空
        }


    }
    public void deleteFile(String virtualPath){
        //1.Prepare full path
        String path = localDir + virtualPath;
        //2.Pack the object
        File file = new File(path);
        //3.Complete delete
        file.delete();
    }
}
